/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.progin.drop.server;

import com.progin.drop.core.OverflowHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author HP
 */
public class StreamHandler extends OverflowHandler {
    private File mTempFile;

    public StreamHandler() {

    }

    public StreamHandler(File targetFile) {
        mTargetFile = targetFile;
    }

    @Override
    public void beforeSave() {
        try {
            mTempFile = new File(mTargetFile.getAbsolutePath() + ".tmp");
            mStream = new FileOutputStream(mTempFile);
        } catch (FileNotFoundException ex) {
            try {
                mTempFile.createNewFile();
                mStream = new FileOutputStream(mTargetFile);
                //Logger.getLogger(StreamHandler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex1) {
                Logger.getLogger(StreamHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex1);
            }
        }
    }

    @Override
    public void save(byte[] b , int count) {
        try {
            mStream.write(b , 0 , (int)count);
        } catch (IOException ex) {
            Logger.getLogger(StreamHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void afterSave() {
        try {
            mStream.close();
            mTempFile.renameTo(new File(mTargetFile.getAbsolutePath()));
        } catch (IOException ex) {
            Logger.getLogger(StreamHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void recoverError() {
        try {
            mStream.close();
        } catch (IOException ex) {
            //Logger.getLogger(StreamHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        mTempFile.delete();
    }

}
